package cn.sxt.common.userscenter.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 发送邮件工具类
 * @author Administrator
 *
 */
@Component("springEmailUtil")
public class SpringEmailUtil {
	@Resource
	private JavaMailSender javaMailSender;
	@Resource
	private SimpleMailMessage simpleMailMessage;
	/**
	 * 发送邮件
	 * @param to
	 * @param subject
	 * @param text
	 * @return
	 */
	public boolean sendEmail(String to,String subject,String text){
		/* 信的内容 */
		try {
			this.simpleMailMessage.setTo(to);
			this.simpleMailMessage.setSubject(subject);
			this.simpleMailMessage.setText(text);
			this.simpleMailMessage.setSentDate(new Date());
			 /* 发送信件 */
			this.javaMailSender.send(this.simpleMailMessage);
			return true;
		} catch (Exception e) {
			ConstantFinalUtil.LOGGER.error("发送失败--to{},subject:{}",to,subject,e);
		}
		return false;
	}
	/**
	 * 		发送邮件解析html
	 * @param to
	 * @param subject
	 * @param text
	 * @return
	 */
	public boolean sendEmailHtml(String to,String subject,String text){
		/* 设置编码 */
		try {
			MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,"UTF-8");
			/* 设置发送信息 */
			helper.setFrom(this.simpleMailMessage.getFrom());
			helper.setTo(to);
			helper.setSubject(subject);
			/* 表示发送的文件是附文件 */
			helper.setText(text,true);
			helper.setSentDate(new Date());
			/* 发送项目 */
			this.javaMailSender.send(mimeMessage);
			ConstantFinalUtil.LOGGER.info("----发送成功----");
			return true;
		} catch (MessagingException e) {
			ConstantFinalUtil.LOGGER.info("----发送失败----");
		}
		return false;
	}
}
